/*
 * $Id: cleanup.c 7557b5d4d82b 2012/12/02 09:07:16 pgurumur $
 *
 * Copyright (c) 2006, 2007, 2008 Prabhu Gurumurthy <pgurumur@gmail.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include "egpd.h"

void
cleanup()
{
	if (conf) {
		while (!LIST_EMPTY(&conf->pfl))  {
			struct prefixlist *tpfl = LIST_FIRST(&conf->pfl);
			LIST_REMOVE(tpfl, entry);
			prefixlistfree(tpfl);
		}

		while (!LIST_EMPTY(&conf->policy)) {
			struct policy *tpol = LIST_FIRST(&conf->policy);
			LIST_REMOVE(tpol, entry);
			policyfree(tpol);
		}

		while (!LIST_EMPTY(&conf->groups)) {
			struct egpd_group *tgroup = LIST_FIRST(&conf->groups);
			LIST_REMOVE(tgroup, entry);
			groupfree(tgroup);
		}

		free(conf);
	}
}

void
stringfree(char *ptr)
{
	if (ptr) {
		free(ptr);

		ptr = NULL;
	}
}

void
groupfree(struct egpd_group *ptr)
{
	u_int8_t ix = 0;
	if (ptr) {
		if (ptr->name) 
			stringfree(ptr->name);

		if (ptr->description)
			stringfree(ptr->description);

		for (ix = 0; ix < ptr->peercnt; ix++) {
			stringfree(ptr->peers[ix].description);
		}

		free(ptr);
		ptr = NULL;
	}
}

void
prefixlistfree(struct prefixlist *ptr)
{
	if (ptr) {
		stringfree(ptr->name);

		memset(ptr->list, 0, sizeof(struct ipaddr));
		free(ptr);
	}
}

void
policyfree(struct policy *ptr)
{
	u_int16_t ix = 0;
	if (ptr) {
		if (ptr->name)
			stringfree(ptr->name);

		if (ptr->description)
			stringfree(ptr->description);

		for (ix = 0; ix < ptr->termcount; ix++) {
			stringfree(ptr->terms[ix].name);
			stringfree(ptr->terms[ix].description);
			memset(&ptr->terms[ix], 0, sizeof(struct policy_term));
		}

		free(ptr);
	}
}
